/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.io.v3;


/**
 * Provides cryptographic functions for encrypting and decrypting databases.
 */
interface Crypto {
    /**
     * Calculates the HMAC for all the unencrypted data.
     * <p>
     * This does not include the tag, salt, or keys in the calculations of the
     * HMAC; nor does it include the field length, type ID, or random padding
     * for each field. The complete fields with type ID and length must still
     * be provided.
     */
    byte[] calculateHmac(byte[] plaintext, byte[] hmacKey);

    /**
     * Calculates the SHA-256 digest of the stretched password.
     */
    byte[] digestKey(byte[] stretchedPw);

    /**
     * Expands the key from the user-entered password using the given salt and
     * the SHA-256 hashing algorithm.
     */
    byte[] stretchKey(byte[] pw, byte[] salt, int iter);

    /**
     * The key from the passphrase is only used to encrypt two
     * randomly-generated keys, one for encrypting records, the other for
     * calculating the HMAC. This decrypts the generated keys.
     *
     * @param data the 32 bytes holding the encrypted key
     * @param stretchedKey the stretched key from the passphrase
     * @return the decrypted 256-bit key
     */
    byte[] decryptKey(byte[] data, byte[] stretchedKey);

    /**
     * The key from the passphrase is only used to encrypt two
     * randomly-generated keys, one for encrypting records, the other for
     * calculating the HMAC. This encrypts the generated keys.
     *
     * @param data the 32 bytes holding the unencrypted key
     * @param stretchedKey the stretched key from the passphrase
     * @return the encrypted 256-bit key
     */
    byte[] encryptKey(byte[] data, byte[] stretchedKey);

    /**
     * Decrypts all records in the given byte array.
     * <p>
     * This expects the first record to start at index 0 in the array. Do
     * not include the DB header fields, the EOF marker, or the HMAC.
     */
    byte[] decryptRecords(byte[] data, byte[] recordKey, byte[] iv);

    /**
     * Encrypts all records in the given byte array.
     * <p>
     * This expects the first record to start at index 0 in the array. Do
     * not include the DB header fields, the EOF marker, or the HMAC.
     */
    byte[] encryptRecords(byte[] data, byte[] recordKey, byte[] iv);
}
